package com.ym.livedemo.api

import com.ym.livedemo.AppApplication
import com.ym.livedemo.Constant
import com.ym.livedemo.getHttpLoggingInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Created by 赵杰 on 2020-01-06.
 */

object ApiServiceClient {
    val loginApiService by lazy {
        return@lazy Retrofit.Builder()
            .client(
                OkHttpClient
                    .Builder()
                    .addInterceptor(getHttpLoggingInterceptor())
                    .addInterceptor(ReceivedCookiesInterceptor(AppApplication.instance.applicationContext))
                    .addInterceptor(AppHttpInterceptor())
                    .addInterceptor { chain ->
                        return@addInterceptor chain.proceed(
                            chain
                                .request()
                                .newBuilder()
                                .addHeader("ClientType", "Android")
                                .build()
                        )
                    }
                    .readTimeout(Constant.READ_TIME_OUT, TimeUnit.SECONDS)
                    .connectTimeout(Constant.CONNECT_TIME_OUT, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true)
                    .build()
            )
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(Constant.BASE_URL)
            .build()
            .create(LoginService::class.java)
    }

    val apiService by lazy {
        return@lazy Retrofit.Builder()
            .client(OkHttpClient()
                .newBuilder()
                .addInterceptor(getHttpLoggingInterceptor())
                .addInterceptor(AppHttpInterceptor())
                .addInterceptor { chain ->
                    return@addInterceptor chain.proceed(
                        chain
                            .request()
                            .newBuilder()
                            .addHeader("Authorization", Constant.TOKEN)
                            .build()
                    )
                }
                .readTimeout(Constant.READ_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(Constant.READ_TIME_OUT, TimeUnit.SECONDS)
                .connectTimeout(Constant.CONNECT_TIME_OUT, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(Constant.BASE_URL)
            .build()
            .create(ApiService::class.java)
    }

}